<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<script src="//cdn.bootcss.com/pace/1.0.2/pace.min.js"></script>
<link href="//cdn.bootcss.com/pace/1.0.2/themes/pink/pace-theme-flash.css" rel="stylesheet">
<style>
    .pace .pace-progress {
        background: #1E92FB; /*进度条颜色*/
        height: 3px;
    }
    .pace .pace-progress-inner {
         box-shadow: 0 0 10px #1E92FB, 0 0 5px     #1E92FB; /*阴影颜色*/
    }
    .pace .pace-activity {
        border-top-color: #1E92FB;    /*上边框颜色*/
        border-left-color: #1E92FB;    /*左边框颜色*/
    }
</style>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">



  <meta name="google-site-verification" content="true">

<script data-ad-client="ca-pub-3331353808689126" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>







  <meta name="baidu-site-verification" content="true">







  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="https://fonts.cat.net/css?family=Lato:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|Lobster Two:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="mysql,索引,">





  <link rel="alternate" href="/atom.xml" title="爱吃jelly的Jelly" type="application/atom+xml">






<meta name="description" content="简介定义索引是 一种特殊的文件 (InnoDB数据表上的索引是表空间的一个组成部分)，它们包含着对数据表里 所有记录的引用指针。 更通俗的说，数据库索引好比是一本书前面的目录，能加快数据库的查询速度。">
<meta name="keywords" content="mysql,索引">
<meta property="og:type" content="article">
<meta property="og:title" content="mysql索引">
<meta property="og:url" content="https://jelly54.github.io/mysql-index/index.html">
<meta property="og:site_name" content="爱吃jelly的Jelly">
<meta property="og:description" content="简介定义索引是 一种特殊的文件 (InnoDB数据表上的索引是表空间的一个组成部分)，它们包含着对数据表里 所有记录的引用指针。 更通俗的说，数据库索引好比是一本书前面的目录，能加快数据库的查询速度。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2020-03-31T13:28:05.382Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="mysql索引">
<meta name="twitter:description" content="简介定义索引是 一种特殊的文件 (InnoDB数据表上的索引是表空间的一个组成部分)，它们包含着对数据表里 所有记录的引用指针。 更通俗的说，数据库索引好比是一本书前面的目录，能加快数据库的查询速度。">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://jelly54.github.io/mysql-index/">






  <meta name="baidu-site-verification" content="t21ZdXzSqf">



<meta name="google-site-verification" content="VmrkZiYJtPrIIH8zlY82aG2_l1Ykrp3JZ3HQbMt0qCo">

  <title>mysql索引 | 爱吃jelly的Jelly</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
    
    <a href="https://github.com/jelly54" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewbox="0 0 250 250" style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"/><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"/><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"/></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">爱吃jelly的Jelly</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">就揪啾  就是 Jelly</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于作者
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://jelly54.github.io/mysql-index/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Big Jelly">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="爱吃jelly的Jelly">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">mysql索引</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-01-18T11:54:59+08:00">
                2020-01-18
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Mysql/" itemprop="url" rel="index">
                    <span itemprop="name">Mysql</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  3.5k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  13
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="简介"><a href="#简介" class="headerlink" title="简介"></a>简介</h1><h2 id="定义"><a href="#定义" class="headerlink" title="定义"></a>定义</h2><p>索引是 <strong>一种特殊的文件</strong> (InnoDB数据表上的索引是表空间的一个组成部分)，它们包含着对数据表里 <strong>所有记录的引用指针。</strong> 更通俗的说，数据库索引好比是一本书前面的目录，能加快数据库的查询速度。</p>
<a id="more"></a>

<p>索引的目的在于提高查询效率，可以类比字典，如果要查“mysql”这个单词，我们肯定需要定位到m字母，然后从下往下找到y字母，再找到剩下的sql。<strong>如果没有索引，那么你可能需要把所有单词看一遍才能找到你想要的</strong> 。除了词典，生活中随处可见索引的例子，如火车站的车次表、图书的目录等。它们的原理都是一样的，<strong>通过不断的缩小想要获得数据的范围来筛选出最终想要的结果，同时把随机的事件变成顺序的事件，也就是我们总是通过同一种查找方式来锁定数据。</strong></p>
<h2 id="作用"><a href="#作用" class="headerlink" title="作用"></a>作用</h2><p>在数据量和访问量不大的情况下，mysql访问是非常快的，是否加索引对访问影响不大。但是<strong>当数据量和访问量剧增的时候，</strong> 就会发现mysql变慢，甚至down掉，这就必须要考虑优化sql了，给数据库建立正确合理的索引，是mysql优化的一个重要手段。  </p>
<p>在创建索引时，需要考虑哪些列会用于 SQL 查询，然后为这些列创建一个或多个索引。事实上，<strong>索引也是一种表，保存着主键或索引字段，以及一个能将每个记录指向实际表的指针。数据库用户是看不到索引的，它们只是用来加速查询的。数据库搜索引擎使用索引来快速定位记录。</strong></p>
<p>INSERT 与 UPDATE 语句在拥有索引的表中执行会花费更多的时间，而SELECT 语句却会执行得更快。这是因为，<strong>在进行插入或更新时，数据库也需要插入或更新索引值。</strong></p>
<h2 id="Mysql索引结构"><a href="#Mysql索引结构" class="headerlink" title="Mysql索引结构"></a>Mysql索引结构</h2><ol>
<li>B-tree索引：</li>
<li>Hash索引：</li>
<li>Full-text全文索引：</li>
<li>R-Tree索引：</li>
</ol>
<hr>
<h1 id="使用"><a href="#使用" class="headerlink" title="使用"></a>使用</h1><h2 id="分类"><a href="#分类" class="headerlink" title="分类"></a>分类</h2><h3 id="INDEX-单值索引"><a href="#INDEX-单值索引" class="headerlink" title="INDEX(单值索引)"></a>INDEX(单值索引)</h3><p>允许出现相同的索引内容，一个索引只包含单个列，一个表可以有多个单列索引。</p>
<h3 id="复合索引"><a href="#复合索引" class="headerlink" title="复合索引"></a>复合索引</h3><p>实质上是将多个字段建到一个索引里，列值的组合必须唯一。</p>
<h3 id="UNIQUE-唯一索引"><a href="#UNIQUE-唯一索引" class="headerlink" title="UNIQUE(唯一索引)"></a>UNIQUE(唯一索引)</h3><p>索引列的值必须唯一，可以有NULL值，NULL可以出现多次。</p>
<h3 id="PRIMARY-KEY-主键索引"><a href="#PRIMARY-KEY-主键索引" class="headerlink" title="PRIMARY  KEY(主键索引)"></a>PRIMARY  KEY(主键索引)</h3><p>不允许出现相同的值，不为NULL。</p>
<h3 id="FULLTEXT-INDEX-全文索引"><a href="#FULLTEXT-INDEX-全文索引" class="headerlink" title="FULLTEXT INDEX(全文索引)"></a>FULLTEXT INDEX(全文索引)</h3><p>可以针对值中的某个单词，但效率不高。</p>
<h2 id="创建-删除-查看"><a href="#创建-删除-查看" class="headerlink" title="创建-删除-查看"></a>创建-删除-查看</h2><h3 id="基本语法"><a href="#基本语法" class="headerlink" title="基本语法"></a>基本语法</h3><figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 创建 </span></span><br><span class="line"><span class="keyword">CREATE</span>  [<span class="keyword">UNIQUE</span>] <span class="keyword">INDEX</span> indexName <span class="keyword">ON</span> mytable(columnname(<span class="keyword">length</span>));</span><br><span class="line"></span><br><span class="line"><span class="keyword">ALTER</span> mytable <span class="keyword">ADD</span> [<span class="keyword">UNIQUE</span>] <span class="keyword">INDEX</span> [indexName] <span class="keyword">ON</span> (columnname(<span class="keyword">length</span>));</span><br><span class="line"></span><br><span class="line"><span class="comment">#删除 </span></span><br><span class="line"><span class="keyword">DROP</span> <span class="keyword">INDEX</span> [indexName] <span class="keyword">ON</span> mytable;</span><br><span class="line"></span><br><span class="line"><span class="comment">#查看 </span></span><br><span class="line"><span class="keyword">SHOW</span> <span class="keyword">INDEX</span> <span class="keyword">FROM</span> table_name;</span><br></pre></td></tr></table></figure>

<h2 id="示例"><a href="#示例" class="headerlink" title="示例"></a>示例</h2><h3 id="使用ALTER-TABLE语句创建索性"><a href="#使用ALTER-TABLE语句创建索性" class="headerlink" title="使用ALTER TABLE语句创建索性"></a>使用ALTER TABLE语句创建索性</h3><p>应用于表创建完毕之后再添加。</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">ALTER</span> <span class="keyword">TABLE</span> 表名 <span class="keyword">ADD</span> 索引类型 （<span class="keyword">unique</span>,primary <span class="keyword">key</span>,fulltext,<span class="keyword">index</span>）[索引名]（字段名）</span><br><span class="line"></span><br><span class="line"><span class="comment"># 普通索引</span></span><br><span class="line"><span class="keyword">ALTER</span> <span class="keyword">TABLE</span> table_name <span class="keyword">ADD</span> <span class="keyword">INDEX</span> index_name (column_list) ;</span><br><span class="line"><span class="comment"># 复合索引</span></span><br><span class="line"><span class="keyword">ALTER</span> <span class="keyword">TABLE</span> table_name <span class="keyword">ADD</span> <span class="keyword">INDEX</span> index_name_name (column_list1,column_list2); </span><br><span class="line"><span class="comment"># 唯一索引</span></span><br><span class="line"><span class="keyword">ALTER</span> <span class="keyword">TABLE</span> table_name <span class="keyword">ADD</span> <span class="keyword">UNIQUE</span> (column_list) ;</span><br><span class="line"><span class="comment"># 主键索引</span></span><br><span class="line"><span class="keyword">ALTER</span> <span class="keyword">TABLE</span> table_name <span class="keyword">ADD</span> PRIMARY <span class="keyword">KEY</span> (column_list) ;</span><br><span class="line"><span class="comment"># 全文索引</span></span><br><span class="line"><span class="keyword">ALTER</span> <span class="keyword">TABLE</span> tbl_name <span class="keyword">ADD</span> FULLTEXT index_name(column_list):</span><br></pre></td></tr></table></figure>

<p>ALTER TABLE可用于索引，<strong>table_name</strong> 是要增加索引的表名，<strong>column_list</strong> 指出对哪些列进行索引，多列时各列之间用 <strong>逗号分隔</strong>。索引名index_name可选，缺省时，MySQL将根据第一个索引列赋一个名称。另外，ALTER TABLE允许在单个语句中更改多个表，因此可以同时创建多个索引。</p>
<h3 id="使用CREATE-INDEX语句对表增加索引"><a href="#使用CREATE-INDEX语句对表增加索引" class="headerlink" title="使用CREATE INDEX语句对表增加索引"></a>使用CREATE INDEX语句对表增加索引</h3><p>CREATE INDEX可用于对表增加普通索引或UNIQUE索引，可用于建表时创建索引。</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">CREATE</span> <span class="keyword">INDEX</span> index_name <span class="keyword">ON</span> table_name(username(<span class="keyword">length</span>)); </span><br><span class="line"></span><br><span class="line"><span class="comment"># 单值索引</span></span><br><span class="line"><span class="keyword">CREATE</span> <span class="keyword">INDEX</span> index_name <span class="keyword">ON</span> table_name (column_list)</span><br><span class="line"><span class="comment"># 唯一索引</span></span><br><span class="line"><span class="keyword">CREATE</span> <span class="keyword">UNIQUE</span> <span class="keyword">INDEX</span> index_name <span class="keyword">ON</span> table_name (column_list)</span><br></pre></td></tr></table></figure>

<p><strong>table_name、index_name</strong> 和 <strong>column_list</strong> 具有与ALTER TABLE语句中相同的含义，索引名不可选。另外，<strong>不能用CREATE INDEX语句创建PRIMARY KEY索引。</strong> 如果是CHAR，VARCHAR类型，length可以小于字段实际长度；如果是BLOB(binary large object) 和TEXT类型，必须指定 length。</p>
<h3 id="删除索引"><a href="#删除索引" class="headerlink" title="删除索引"></a>删除索引</h3><p>删除索引可以使用<strong>ALTER TABLE</strong> 或 <strong>DROP INDEX</strong>语句来实现。DROP INDEX可以在ALTER TABLE内部作为一条语句处理，其格式如下：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">DROP</span> <span class="keyword">INDEX</span> index_name <span class="keyword">ON</span> table_name ;</span><br><span class="line"></span><br><span class="line"><span class="keyword">ALTER</span> <span class="keyword">TABLE</span> table_name <span class="keyword">DROP</span> <span class="keyword">INDEX</span> index_name ;</span><br><span class="line"></span><br><span class="line"><span class="keyword">ALTER</span> <span class="keyword">TABLE</span> table_name <span class="keyword">DROP</span> PRIMARY <span class="keyword">KEY</span> ;</span><br></pre></td></tr></table></figure>

<p>其中，在前面的两条语句中，都删除了table_name中的索引index_name。而在最后一条语句中，只在删除PRIMARY KEY索引中使用，因为一个表只可能有一个PRIMARY KEY索引，因此不需要指定索引名。如果没有创建PRIMARY KEY索引，但表具有一个或多个UNIQUE索引，则MySQL将删除第一个UNIQUE索引。</p>
<p><strong>如果从表中删除某列，则索引会受影响。</strong> 对于多列组合的索引，如果删除其中的某列，则该列也会从索引中删除。如果删除组成索引的所有列，则整个索引将被删除。</p>
<p>–</p>
<h1 id="探究"><a href="#探究" class="headerlink" title="探究"></a>探究</h1><h2 id="组合索引-amp-左前缀原则"><a href="#组合索引-amp-左前缀原则" class="headerlink" title="组合索引&amp;左前缀原则"></a>组合索引&amp;左前缀原则</h2><p>组合索引和前缀索引是对建立索引技巧的一种称呼，并不是索引的类型</p>
<h3 id="示例："><a href="#示例：" class="headerlink" title="示例："></a>示例：</h3><figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">ALTER</span> <span class="keyword">TABLE</span> user_demo <span class="keyword">ADD</span> <span class="keyword">INDEX</span> name_city_age (login_name(<span class="number">16</span>),city,age);</span><br></pre></td></tr></table></figure>

<p>建表时，login_name 长度为100，这里用16(前16位有很好的区分度)，<strong>这样会加快索引查询速度，还会减少索引文件的大小，提高INSERT，UPDATE的更新速度。</strong></p>
<p>建立这样的组合索引，就相当于分别建立如下三种组合索引：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">login_name,city,age</span><br><span class="line">login_name,city</span><br><span class="line">login_name</span><br></pre></td></tr></table></figure>

<p>为什么没有city, age等这样的组合索引呢？这是因为 <strong>mysql组合索引“最左前缀”</strong> 的结果。简单的理解就是只从最左边的开始组合，并不是只要包含这三列的查询都会用到该组合索引。也就是说name_city_age(LOGIN_NAME(16),CITY,AGE) <strong>从左到右进行索引，如果没有左前索引，mysql不会执行索引查询。</strong></p>
<h3 id="Tips"><a href="#Tips" class="headerlink" title="Tips"></a>Tips</h3><p>如果索引列长度过长,这种列索引时将会产生很大的索引文件,不便于操作,可以使用前缀索引方式进行索引，<strong>前缀索引应该控制在一个合适的点,控制在0.31黄金值即可(大于这个值就可以创建)。</strong></p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 这个值大于0.31就可以创建前缀索引,Distinct去重复</span></span><br><span class="line"><span class="keyword">SELECT</span> <span class="keyword">COUNT</span>(<span class="keyword">DISTINCT</span>(<span class="keyword">LEFT</span>(<span class="string">`title`</span>,<span class="number">10</span>))) / <span class="keyword">COUNT</span>(*) <span class="keyword">FROM</span> pages; <span class="comment">--</span></span><br></pre></td></tr></table></figure>

<h2 id="索引分析"><a href="#索引分析" class="headerlink" title="索引分析"></a>索引分析</h2><h3 id="单表索引"><a href="#单表索引" class="headerlink" title="单表索引"></a>单表索引</h3><ol>
<li>索引index1:(a,b,c)，只会走a、a,b、a,b,c 三种类型的查询。</li>
<li>其实 a,c也走，但是只走a字段索引，不会走c字段。</li>
<li>同时，<strong><em>SELECT * FROM table WHERE a = ‘1’ AND b &gt; ‘2’ AND c=’3’;</em></strong>  这种类型的也只会有a与b走索引，<strong>c不会走。</strong></li>
<li>尽量使用等值查询，减少范围查询，能最大程度避免索引失效。</li>
</ol>
<p><strong>原因如下：</strong></p>
<p>索引是有序的，index1索引在索引文件中的排列是有序的，首先根据a来排序，然后才是根据b来排序，最后是根据c来排序，</p>
<p>像 <em>select * from table where a = ‘1’ and b &gt; ‘2’ and c=’3’;</em> 这种类型的sql语句，在a走完索引后，b使用索引进行范围查找，<strong>c肯定是无序了</strong>，所以c就没法走索引，数据库会觉得还不如全表扫描c字段来的快。</p>
<blockquote>
<p>如果分别给login_name, city, age 建立单列索引，<strong>让该表有3个单列索引，查询时和组合索引的效率是大不一样的，甚至远远低于组合索引。</strong> 虽然此时有三个索引，但mysql只能用到其中的那个它认为似乎是最有效率的单列索引，另外两个是用不到的，也就是说还是一个全表扫描的过程。  </p>
</blockquote>
<h3 id="两表索引"><a href="#两表索引" class="headerlink" title="两表索引"></a>两表索引</h3><p>LEFT JOIN 索引加右表。<br>RIGHT JOIN 索引加在左表。</p>
<blockquote>
<p>做链接用于确定如何从右表进行搜索，左边数据一定都会有，所以右表是检索的关键，要加索引。若左表加索引，右表没有则会出现两次全表扫描。</p>
</blockquote>
<h3 id="三表索引"><a href="#三表索引" class="headerlink" title="三表索引"></a>三表索引</h3><p>JOIN 语句优化</p>
<ol>
<li>尽可能减少join语句中的NestedLoop的循环总次数：永远使用小结果集驱动大结果集。</li>
<li>优先优化NestedLoop的内层循环。</li>
<li>保证join语句中被驱动表上join条件字段已经被索引。</li>
<li>当无法保证被驱动表的join条件字段被索引且内存资源充足的前提下，不要太吝啬JoinBuffer的设置。</li>
</ol>
<h2 id="索引失效"><a href="#索引失效" class="headerlink" title="索引失效"></a>索引失效</h2><ol>
<li><p>全值匹配</p>
</li>
<li><p>最佳左前缀法则</p>
</li>
<li><p>不在索引列上做任何操作<br>计算、函数、(自动或手动)类型转换，会导致索引失效，进而导致全表扫描</p>
</li>
<li><p>索引在 范围查询后会失效。</p>
</li>
<li><p>尽量使用覆盖索引</p>
</li>
<li><p>mysql在使用(!=, &lt;&gt;)的时候无法使用索引，会导致全表扫描。</p>
</li>
<li><p>is null，is not null 无法使用索引。<br>is null 会从另外的记录中读取，is not null将会进行全表扫描。</p>
</li>
<li><p>like 以通配符开头(%abc) mysql 索引将会变成全表扫描。</p>
</li>
</ol>
<p><strong>两边都是%的like查询，应使用覆盖索引。即在查询的字段列表中(select xxx from···)只是用索引中的字段。将会使用index 索引。</strong></p>
<ol start="9">
<li><p>字符串不加单引号索引失效。会导致自动的类型转换。</p>
</li>
<li><p>少用 or，用它来连接时会索引失效。 </p>
</li>
</ol>
<h2 id="BAD-SQL"><a href="#BAD-SQL" class="headerlink" title="BAD SQL"></a>BAD SQL</h2><figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># -- 正则表达式不使用索引,这应该很好理解</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 不会使用索引,因为所有索引列参与了计算</span></span><br><span class="line"><span class="keyword">SELECT</span> <span class="string">`sname`</span> <span class="keyword">FROM</span> <span class="string">`stu`</span> <span class="keyword">WHERE</span> <span class="string">`age`</span>+<span class="number">10</span>=<span class="number">30</span>; </span><br><span class="line"></span><br><span class="line"><span class="comment"># 不会使用索引,因为使用了函数运算,原理与上面相同</span></span><br><span class="line"><span class="keyword">SELECT</span> <span class="string">`sname`</span> <span class="keyword">FROM</span> <span class="string">`stu`</span> <span class="keyword">WHERE</span> <span class="keyword">LEFT</span>(<span class="string">`date`</span>,<span class="number">4</span>) &lt;<span class="number">1990</span>;   </span><br><span class="line"></span><br><span class="line"><span class="comment"># 走索引</span></span><br><span class="line"><span class="keyword">SELECT</span> * <span class="keyword">FROM</span> <span class="string">`houdunwang`</span> <span class="keyword">WHERE</span> <span class="string">`uname`</span> <span class="keyword">LIKE</span><span class="string">'后盾%'</span>;  </span><br><span class="line"></span><br><span class="line"><span class="comment"># 不走索引</span></span><br><span class="line"><span class="keyword">SELECT</span> * <span class="keyword">FROM</span> <span class="string">`houdunwang`</span> <span class="keyword">WHERE</span> <span class="string">`uname`</span> <span class="keyword">LIKE</span> <span class="string">"%后盾%"</span>;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># -- 字符串与数字比较不使用索引;</span></span><br><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> <span class="string">`a`</span> (<span class="string">`a`</span> <span class="built_in">char</span>(<span class="number">10</span>));</span><br><span class="line"></span><br><span class="line"><span class="comment"># 走索引</span></span><br><span class="line"><span class="keyword">EXPLAIN</span> <span class="keyword">SELECT</span> * <span class="keyword">FROM</span> <span class="string">`a`</span> <span class="keyword">WHERE</span> <span class="string">`a`</span>=<span class="string">"1"</span>;</span><br><span class="line"><span class="comment"># 不走索引</span></span><br><span class="line"><span class="keyword">EXPLAIN</span> <span class="keyword">SELECT</span> * <span class="keyword">FROM</span> <span class="string">`a`</span> <span class="keyword">WHERE</span> <span class="string">`a`</span>=<span class="number">1</span>;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># -- 如果条件中有or,即使其中有条件带索引也不会使用。</span></span><br><span class="line"><span class="comment"># 换言之,就是要求使用的所有字段,都必须建立索引, 我们建议大家尽量避免使用or 关键字</span></span><br><span class="line"><span class="keyword">select</span> * <span class="keyword">from</span> dept <span class="keyword">where</span> dname=<span class="string">'xxx'</span> <span class="keyword">or</span> loc=<span class="string">'xx'</span> <span class="keyword">or</span> deptno=<span class="number">45</span>;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># -- 如果mysql估计使用全表扫描要比使用索引快,则不使用索引</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># index(a1, a2, a3, a4)</span></span><br><span class="line"><span class="comment"># 使用了索引，a3作用在排序而不是查找</span></span><br><span class="line"><span class="keyword">select</span> * <span class="keyword">from</span> test_table <span class="keyword">where</span> a1=<span class="string">'a1'</span> <span class="keyword">and</span> a2=<span class="string">'a2'</span> <span class="keyword">and</span> a4=<span class="string">'a4'</span> <span class="keyword">order</span> <span class="keyword">by</span> a3;</span><br><span class="line"></span><br><span class="line"><span class="comment"># 用到索引，但是由于a3没有出现，出现了a4，将出现filesort。</span></span><br><span class="line"><span class="keyword">select</span> * <span class="keyword">from</span> test_table <span class="keyword">where</span> a1=<span class="string">'a1'</span> <span class="keyword">and</span> a2=<span class="string">'a2'</span> <span class="keyword">order</span> <span class="keyword">by</span> a4;</span><br><span class="line"></span><br><span class="line"><span class="comment"># 只使用了a1一个字段索引，但是a2, a3用于排序，无filesort。</span></span><br><span class="line"><span class="keyword">select</span> * <span class="keyword">from</span> test_table <span class="keyword">where</span> a1=<span class="string">'a1'</span> <span class="keyword">and</span> a5=<span class="string">'a5'</span> <span class="keyword">order</span> <span class="keyword">by</span> a2, a3;</span><br><span class="line"></span><br><span class="line"><span class="comment"># 出现filesort，索引为1，2，3，4 但是order by 没有按顺序。</span></span><br><span class="line"><span class="keyword">select</span> * <span class="keyword">from</span> test_table <span class="keyword">where</span> a1=<span class="string">'a1'</span> <span class="keyword">and</span> a5=<span class="string">'a5'</span> <span class="keyword">order</span> <span class="keyword">by</span> a3, a2;</span><br><span class="line"></span><br><span class="line"><span class="comment"># 虽然order by顺序错误，但是前边已经定义a2，即a2已经是常量了，排序不关心，不会产生filesort。</span></span><br><span class="line"><span class="keyword">select</span> * <span class="keyword">from</span> test_table <span class="keyword">where</span> a1=<span class="string">'a1'</span> <span class="keyword">and</span> a2=<span class="string">'a2'</span> <span class="keyword">order</span> <span class="keyword">by</span> a3, a2;</span><br><span class="line"></span><br><span class="line"><span class="comment"># 出现filesort，temporary，where 很惨。</span></span><br><span class="line"><span class="keyword">select</span> * <span class="keyword">from</span> test_table <span class="keyword">where</span> a1=<span class="string">'a1'</span> <span class="keyword">and</span> a4=<span class="string">'a4'</span> <span class="keyword">group</span> <span class="keyword">by</span> a3,a2;</span><br></pre></td></tr></table></figure>

<p>定值、范围还是排序，一般order by是给个范围</p>
<p>group by基本上都是需要进行排序，会有临时表产生</p>
<hr>
<h1 id="一般性建议"><a href="#一般性建议" class="headerlink" title="一般性建议"></a>一般性建议</h1><h2 id="什么时候需要建立索引"><a href="#什么时候需要建立索引" class="headerlink" title="什么时候需要建立索引"></a>什么时候需要建立索引</h2><ol>
<li>主键自动建立唯一索引。</li>
<li>频繁作为查询条件的字段应该创建索引。</li>
<li>查询中与其他表关联的字段，外键关系建立索引。</li>
<li>单键/组合索引的选择。选择组合索引。（高并发倾向于组合索引）</li>
<li>Where条件里用不到的字段不创建索引</li>
<li>查询中统计或者分组的字段要创建索引</li>
<li>查询中排序的字段，排序字段若通过索引去访问将大大提高排序速度。</li>
</ol>
<h2 id="什么时候不建议建立索引"><a href="#什么时候不建议建立索引" class="headerlink" title="什么时候不建议建立索引"></a>什么时候不建议建立索引</h2><ol>
<li>表记录太少。（三百万以下）</li>
<li>经常增删改的表。提高了查询速度，但是会降低更新表的速度，更新表的时候，不仅要保存数据，还要保存索引。</li>
<li>数据重复且分布平均的表字段。</li>
</ol>
<h2 id="tips"><a href="#tips" class="headerlink" title="tips"></a>tips</h2><ol>
<li>索引不会包含有NULL的列</li>
</ol>
<p><strong>只要列中包含有NULL值，都将不会被包含在索引中</strong>，复合索引中只要有一列含有NULL值，那么这一列对于此符合索引就是无效的。</p>
<ol start="2">
<li>索引列排序</li>
</ol>
<p><strong>mysql查询只使用一个索引</strong>，因此如果where子句中已经使用了索引的话，那么order by中的列是不会使用索引的。因此数据库默认排序可以符合要求的情况下不要使用排序操作，尽量不要包含多个列的排序，如果需要最好给这些列建复合索引。</p>
<ol start="3">
<li>like语句操作</li>
</ol>
<p>一般情况下不鼓励使用like操作，如果非使用不可，注意正确的使用方式。like ‘%aaa%’不会使用索引，而like ‘aaa%’可以使用索引。</p>
<ol start="4">
<li><p>不要在列上进行运算</p>
</li>
<li><p>不使用NOT IN 、&lt;&gt;、！=操作，但 <strong>&lt;,&lt;=，=，&gt;,&gt;=,BETWEEN,IN是可以用到索引的.</strong></p>
</li>
<li><p>在where和join中出现的列需要建立索引。</p>
</li>
<li><p>如果where字句的查询条件里使用了函数(如：where DAY(column)=…),mysql将无法使用索引。</p>
</li>
<li><p>在join操作中(需要从多个数据表提取数据时)，mysql只有在 <strong>主键和外键的数据类型相同时</strong> 才能使用索引，否则及时建立了索引也不会使用。</p>
</li>
</ol>

      
    </div>
    
    
    
    <div>
      
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束 <i class="fa fa-paw"></i> 感谢您的阅读-------------</div>
    
</div>

      
    </div>
    <div>
      
        
<div class="my_post_copyright">
  <script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script>
  
  <!-- JS库 sweetalert 可修改路径 -->
  <script src="https://cdn.bootcss.com/jquery/2.0.0/jquery.min.js"></script>
  <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
  <p><span>本文标题:</span><a href="/mysql-index/">mysql索引</a></p>
  <p><span>文章作者:</span><a href="/" title="访问 Big Jelly 的个人博客">Big Jelly</a></p>
  <p><span>发布时间:</span>2020年01月18日 - 11:54</p>
  <p><span>最后更新:</span>2020年03月31日 - 21:28</p>
  <p><span>原始链接:</span><a href="/mysql-index/" title="mysql索引">https://jelly54.github.io/mysql-index/</a>
    <span class="copy-path" title="点击复制文章链接"><i class="fa fa-clipboard" data-clipboard-text="https://jelly54.github.io/mysql-index/" aria-label="复制成功！"></i></span>
  </p>
  <p><span>许可协议:</span><i class="fa fa-creative-commons"></i> <a rel="license" href="https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)">署名-非商业性使用-禁止演绎 4.0 国际</a> 转载请保留原文链接及作者。</p>  
</div>
<script> 
    var clipboard = new Clipboard('.fa-clipboard');
      $(".fa-clipboard").click(function(){
      clipboard.on('success', function(){
        swal({   
          title: "",   
          text: '复制成功',
          icon: "success", 
          showConfirmButton: true
          });
        });
    });  
</script>

      
    </div>
    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.png" alt="Big Jelly 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.png" alt="Big Jelly 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/mysql/" rel="tag"><i class="fa fa-tag"></i> mysql</a>
          
            <a href="/tags/索引/" rel="tag"><i class="fa fa-tag"></i> 索引</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/mysql-b-tree/" rel="next" title="mysql为什么使用B+树">
                <i class="fa fa-chevron-left"></i> mysql为什么使用B+树
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/mysql-query-optimization/" rel="prev" title="mysql查询优化">
                mysql查询优化 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
	<div id="gitalk-container"></div>

  

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- 展示广告 -->
<ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-3331353808689126" data-ad-slot="4663393885" data-ad-format="auto" data-full-width-responsive="true"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/avatar.jpg" alt="Big Jelly">
            
              <p class="site-author-name" itemprop="name">Big Jelly</p>
              <p class="site-description motion-element" itemprop="description">Nothing is easier than to deceive oneself</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">55</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">68</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a rel="external nofollow" href="https://github.com/jelly54" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a rel="external nofollow" href="mailto:jelly_54@163.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                外链小站
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://leetcode.com/" title="LeetCode" rel="external nofollow" target="_blank">LeetCode</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.dooccn.com/" title="在线编辑代码" rel="external nofollow" target="_blank">在线编辑代码</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.chuangzaoshi.com/code" title="创造狮导航" rel="external nofollow" target="_blank">创造狮导航</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://24mail.chacuo.net/?utm_campaign=haruki&utm_content=note&utm_medium=reader_share&utm_source=qq" title="24Mail" rel="external nofollow" target="_blank">24Mail</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://e.xitu.io/" title="掘金酱" rel="external nofollow" target="_blank">掘金酱</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#简介"><span class="nav-number">1.</span> <span class="nav-text">简介</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#定义"><span class="nav-number">1.1.</span> <span class="nav-text">定义</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#作用"><span class="nav-number">1.2.</span> <span class="nav-text">作用</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Mysql索引结构"><span class="nav-number">1.3.</span> <span class="nav-text">Mysql索引结构</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#使用"><span class="nav-number">2.</span> <span class="nav-text">使用</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#分类"><span class="nav-number">2.1.</span> <span class="nav-text">分类</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#INDEX-单值索引"><span class="nav-number">2.1.1.</span> <span class="nav-text">INDEX(单值索引)</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#复合索引"><span class="nav-number">2.1.2.</span> <span class="nav-text">复合索引</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#UNIQUE-唯一索引"><span class="nav-number">2.1.3.</span> <span class="nav-text">UNIQUE(唯一索引)</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#PRIMARY-KEY-主键索引"><span class="nav-number">2.1.4.</span> <span class="nav-text">PRIMARY  KEY(主键索引)</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#FULLTEXT-INDEX-全文索引"><span class="nav-number">2.1.5.</span> <span class="nav-text">FULLTEXT INDEX(全文索引)</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#创建-删除-查看"><span class="nav-number">2.2.</span> <span class="nav-text">创建-删除-查看</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#基本语法"><span class="nav-number">2.2.1.</span> <span class="nav-text">基本语法</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#示例"><span class="nav-number">2.3.</span> <span class="nav-text">示例</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#使用ALTER-TABLE语句创建索性"><span class="nav-number">2.3.1.</span> <span class="nav-text">使用ALTER TABLE语句创建索性</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用CREATE-INDEX语句对表增加索引"><span class="nav-number">2.3.2.</span> <span class="nav-text">使用CREATE INDEX语句对表增加索引</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#删除索引"><span class="nav-number">2.3.3.</span> <span class="nav-text">删除索引</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#探究"><span class="nav-number">3.</span> <span class="nav-text">探究</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#组合索引-amp-左前缀原则"><span class="nav-number">3.1.</span> <span class="nav-text">组合索引&amp;左前缀原则</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#示例："><span class="nav-number">3.1.1.</span> <span class="nav-text">示例：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Tips"><span class="nav-number">3.1.2.</span> <span class="nav-text">Tips</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#索引分析"><span class="nav-number">3.2.</span> <span class="nav-text">索引分析</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#单表索引"><span class="nav-number">3.2.1.</span> <span class="nav-text">单表索引</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#两表索引"><span class="nav-number">3.2.2.</span> <span class="nav-text">两表索引</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#三表索引"><span class="nav-number">3.2.3.</span> <span class="nav-text">三表索引</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#索引失效"><span class="nav-number">3.3.</span> <span class="nav-text">索引失效</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#BAD-SQL"><span class="nav-number">3.4.</span> <span class="nav-text">BAD SQL</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#一般性建议"><span class="nav-number">4.</span> <span class="nav-text">一般性建议</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#什么时候需要建立索引"><span class="nav-number">4.1.</span> <span class="nav-text">什么时候需要建立索引</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#什么时候不建议建立索引"><span class="nav-number">4.2.</span> <span class="nav-text">什么时候不建议建立索引</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#tips"><span class="nav-number">4.3.</span> <span class="nav-text">tips</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

      <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
      <!-- 侧边栏广告 -->
      <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-3331353808689126" data-ad-slot="7563237003" data-ad-format="auto" data-full-width-responsive="true"></ins>
      <script>
      	(adsbygoogle = window.adsbygoogle || []).push({});
      </script>
    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright"> &copy; 2017 &mdash; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Big Jelly</span>

</div>

<div class="powered-by">
	
		<span class="post-meta-item-icon">
			<i class="fa fa-area-chart"></i>
		</span>
		
			<span class="post-meta-item-text">Site words total count&#58;</span>
		
		<span title="Site words total count">140.8k</span>
	
  
	
		<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

		<span class="post-meta-divider">|</span>
		<span class="post-visit-item-icon">
			<i class="fa fa-user-md"></i>
		</span>
		<span class="busuanzi_container_site_uv">
			Visitors to this site: <span id="busuanzi_value_site_uv"></span>
		</span>
	
  


	
</div>
        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  <link rel="stylesheet" href="https://unpkg.com/gitalk/dist/gitalk.css">
  <script src="https://unpkg.com/gitalk/dist/gitalk.min.js"></script>
  <script src="/js/md5.min.js"></script>
   <script type="text/javascript">
        var gitalk = new Gitalk({
          clientID: 'ca31692554c3aea431f0',
          clientSecret: '1173c9e9c3c9038304c9a5b08929a359cae9f847',
          repo: 'jelly54.github.io',
          owner: 'jelly54',
          admin: ['jelly54'],
          id: md5(location.pathname),
          distractionFreeMode: 'true'
        })
        gitalk.render('gitalk-container')
       </script>

  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  



  
<script type="text/javascript" color="0,0,255" opacity="0.7" zindex="-2" count="99" src="//cdn.bootcss.com/canvas-nest.js/1.0.0/canvas-nest.min.js"></script>


<!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/src/love.js"></script>
<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"log":true,"model":{"scale":1,"jsonPath":"/live2dw/assets/miku.model.json"},"display":{"position":"right","width":200,"height":400,"hOffset":0,"vOffset":-5},"mobile":{"show":true,"scale":0.5},"react":{"opacity":0.9},"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/","tagMode":false});</script></body>
</html>
